package CategoryService

import (
	"context"
	"gdshop-admin-go-api/app/request/BaseReq"
	"gdshop-admin-go-api/library/response"
	toolsDb "gdshop-admin-go-api/library/tools/db"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/util/gconv"
	"time"
)

// Delete 分类删除，递归删除
func Delete(r *ghttp.Request, req *BaseReq.I) *response.JsonResponse {
	ctx := r.GetCtx()
	data := g.Map{
		"delete_at": time.Now().Unix(),
	}
	// 编辑前方法
	if req.DeleteBeforeFn != nil {
		respRes := req.DeleteBeforeFn(r, data)
		if respRes.Code != 0 {
			return respRes
		}
	}
	_, err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, req.TableName).Where(
		"id",
		gconv.SliceAny(req.Ids),
	).Update(data)
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	delCategoryByParentIds(ctx, gconv.SliceAny(req.Ids), data)
	return response.SuccessByRequestMessage(nil, "删除成功")
}

// 递归删除
func delCategoryByParentIds(ctx context.Context, parentIds []interface{}, data g.Map) {
	// 如果没有数据的话，停止执行
	if len(parentIds) < 1 {
		return
	}
	// 先查出当前 传入的父类ID
	res, err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "category").Where(
		"parent_id",
		gconv.SliceAny(parentIds),
	).Fields("id").Array()
	if err != nil {
		return
	}
	// 执行删除
	toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "category").Where(
		"parent_id",
		gconv.SliceAny(parentIds),
	).Update(data)

	// 递归
	delCategoryByParentIds(ctx, gconv.SliceAny(res), data)
}
